package com.sky.task;

import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.operator.Equal;
import com.ejlchina.searcher.operator.LessThan;
import com.ejlchina.searcher.util.MapUtils;
import com.sky.constant.OrderConstant;
import com.sky.entity.Orders;
import com.sky.service.OrderService;
import com.sky.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author tzl
 * @Date 2023/8/1 17:48  星期二
 * @ClassName OrderTask
 * @Description 订单的定时任务类
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderService orderService;

    @Autowired
    private BeanSearcher beanSearcher;


    /**
     * @Author tzl
     * @Description 处理超时订单的定时任务
     *  每分钟触发一次
     * @Date 2023/8/2  10:15
     **/
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrder(){
        Date nowDate = DateUtils.getNowDate();
        // 获取当前时间
        log.info("处理超时订单 {}", nowDate);
        Map<String, Object> build = MapUtils.builder()
                .field(Orders::getStatus, OrderConstant.PENDING_PAYMENT).op(Equal.class)
                .field(Orders::getOrderTime,DateUtils.minusMinutes(15)).op(LessThan.class)
                .build();
        List<Orders> ordersList = beanSearcher.searchAll(Orders.class, build);
        if(!CollectionUtils.isEmpty(ordersList)){
            ordersList.forEach(item ->{
                item.setStatus(OrderConstant.CANCELLED);
                item.setCancelTime(nowDate);
                item.setCancelReason("订单超时，自动取消");
                orderService.updateById(item);
            });
        }
    }


    /**
     * @Author tzl 
     * @Description 处理派送中的订单的定时任务
     * @Date 2023/8/2  11:21
     **/
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        Date nowDate = DateUtils.getNowDate();
        log.info("定时处理处于派送中的订单，{}",nowDate);
        Map<String, Object> build = MapUtils.builder()
                .field(Orders::getStatus, OrderConstant.DELIVERY_IN_PROGRESS).op(Equal.class)
                .field(Orders::getOrderTime,DateUtils.minusMinutes(60)).op(LessThan.class)
                .build();
        List<Orders> ordersList = beanSearcher.searchAll(Orders.class, build);
        if(!CollectionUtils.isEmpty(ordersList)){
            ordersList.forEach(item ->{
                item.setStatus(OrderConstant.COMPLETED);
                orderService.updateById(item);
            });
        }
    }
}
